package com.iss.wyy.servlet;

import com.iss.wyy.bean.Data;
import com.iss.wyy.bean.Handler;
import com.iss.wyy.bean.Param;
import com.iss.wyy.bean.View;
import com.iss.wyy.common.RequestMethod;
import com.iss.wyy.helper.BeanHelper;
import com.iss.wyy.helper.ControllerHelper;
import com.iss.wyy.helper.HelperLoader;
import com.iss.wyy.helper.PropertiesHelper;
import com.iss.wyy.util.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求转发器
 */
@WebServlet(urlPatterns = "/",loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("111111111111111111111111111111111111111111111111111111111");
        //初始化相关Helper类
        HelperLoader.init();
        //获取ServletContext对象（用于注册Servlet）
        ServletContext servletContext = config.getServletContext();
        //注册处理jsp的servlet
        /*ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(PropertiesHelper.getAppJspPath()+"*");*/
        //注册处理静态资源的默认servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(PropertiesHelper.getAppAssetPath()+"*");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求方法与请求路径
        String requestMethod = req.getMethod();
        String requestPath = req.getRequestURI();
        System.out.println("requestpath--------------"+requestPath);
        //获取Controller处理器
        Handler handler = ControllerHelper.getHandler(RequestMethod.getMethod(requestMethod),requestPath);
        if(handler!=null){
            //获取Controller类及其bean实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            //创建请求参数对象
            Param param = new Param(creatParam(req));
            //调用controller方法
            Method controllerMethod = handler.getRequestMappingMethod();
            Object result = ReflectionUtil.invokeMethod(controllerBean,controllerMethod,param);
            //处理controller返回值
            if (result instanceof View){
                view(req, resp, (View) result);
            }else if(result instanceof Data){
                json(resp, (Data) result);
            }
        }
    }

    /**
     * json的处理器
     * @param resp
     * @param result
     * @throws IOException
     */
    private void json(HttpServletResponse resp, Data result) throws IOException {
        //返回json数据
        Data data = result;
        Object model = data.getModel();
        if (model!=null){
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter writer = resp.getWriter();
            String json = JsonUtil.toJson(model);
            writer.write(json);
            writer.flush();
            writer.close();
        }
    }

    /**
     * view处理器
     * @param req
     * @param resp
     * @param
     * @throws IOException
     * @throws ServletException
     */
    private void view(HttpServletRequest req, HttpServletResponse resp, View view) throws IOException, ServletException {
        //返回jsp页面
        String path = view.getPath();
        if (StringUtils.isNotEmpty(path)){
            if(path.startsWith("/")){
                //重定向
                resp.sendRedirect(req.getContextPath()+path);
            }else{
                //封装转发的model参数 到request
                Map<String,Object> model = view .getModel();
                for (Map.Entry<String, Object> entry : model.entrySet()){
                    req.setAttribute(entry.getKey(),entry.getValue());
                }
                //请求转发到jsp
                req.getRequestDispatcher(PropertiesHelper.getAppJspPath()+path).forward(req,resp);
            }
        }
    }

    /**
     * 请求参数封装
     * @param req
     * @return
     * @throws IOException
     */
    private Map<String ,Object> creatParam(HttpServletRequest req) throws IOException {
        Map<String ,Object> paramMap = new HashMap<>();
        Enumeration<String> paramNames = req.getParameterNames();
        while (paramNames.hasMoreElements()){
            String paramName = paramNames.nextElement();
            String paramValue =req.getParameter(paramName);
            paramMap.put(paramName,paramValue);
        }
        String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
        if(StringUtils.isNotEmpty(body)){
            String[] params = StringUtils.split(body,"&");
            if(ArrayUtils.isNotEmpty(params)){
                for (String param :params) {
                    String[] array = StringUtils.split(param,"=");
                    if (ArrayUtils.isNotEmpty(array)){
                        String paramName = array[0];
                        String paramValue = array[1];
                        paramMap.put(paramName,paramValue);
                    }
                }
            }
        }
        return paramMap;
    }

}
